﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebSite.App_Code;
using WebSite.App_Data;
using WebSite.Models;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using System.Web.Configuration;

namespace WebSite.Controllers
{
    public class DownloadController : BaseController
    {
        //
        // GET: /Download/

        public ActionResult QueryBudget(int id)
        {

            List<vw_Budget> Data = new List<vw_Budget>();

            QueryModel QM = new QueryModel();
            QM.U = this.CurrentUser;
            QM.Where_Year = this.CurrentYear;

            QM.SetQueryString(Request.QueryString);

            QM.Where_IsHis = false;

            QM.Query();

            Data = QM.QueryResult;

            if (Data.Count == 0)
            {
                ViewData["DB.Operation.Result"] = "没有任何下载";
                return View();
            }

            if (id == 1)
            {
                #region ExportExcel

                String strTempPath = Server.MapPath(WebConfigurationManager.AppSettings["DownloadTmpPath"]) + Guid.NewGuid().ToString().Replace("-", "") + ".xls";
                System.IO.File.Copy(Server.MapPath(WebConfigurationManager.AppSettings["TemplatePath"] + "ProjectTemplate.xls"), strTempPath);

                Excel._Application app = null;
                Excel.Workbook book = null;
                Excel.Worksheet ws = null;
                ExcelUilityItem XlTools = new ExcelUilityItem();

                try
                {
                    app = new Excel.ApplicationClass();

                    app.AutomationSecurity = Microsoft.Office.Core.MsoAutomationSecurity.msoAutomationSecurityForceDisable;
                    book = app.Workbooks.Open(strTempPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                    , Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                                    , Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                    ws = (Excel.Worksheet)book.Worksheets.get_Item(1);

                    ws.UsedRange.Validation.Delete();

                    int i = 3;

                    foreach (vw_Budget One in Data)
                    {
                        ws.get_Range("A" + i.ToString()).Value2 = One.ProjectCategoryName;
                        ws.get_Range("B" + i.ToString()).Value2 = One.BudgetYear;
                        ws.get_Range("C" + i.ToString()).Value2 = One.ProjectTypeName;
                        ws.get_Range("D" + i.ToString()).Value2 = One.DepartmentName;
                        ws.get_Range("E" + i.ToString()).Value2 = One.ProjectName;
                        ws.get_Range("F" + i.ToString()).Value2 = One.ProjectCode;
                        ws.get_Range("G" + i.ToString()).Value2 = One.AnnualProgress;
                        ws.get_Range("H" + i.ToString()).Value2 = One.FundsSources;
                        ws.get_Range("I" + i.ToString()).Value2 = CommonItem.X_yyyyMMdd(One.ProjectBeginTime);
                        ws.get_Range("J" + i.ToString()).Value2 = CommonItem.X_yyyyMMdd(One.ProjectEndTime);
                        ws.get_Range("K" + i.ToString()).Value2 = One.ProjectPICName;
                        ws.get_Range("L" + i.ToString()).Value2 = One.IsSoft;
                        ws.get_Range("M" + i.ToString()).Value2 = One.BudgetStatusName;
                        ws.get_Range("N" + i.ToString()).Value2 = One.IsAdvence;
                        ws.get_Range("O" + i.ToString()).Value2 = One.AdvencePlanAmount;
                        ws.get_Range("P" + i.ToString()).Value2 = CommonItem.X_yyyyMMdd(One.AdvencePlanTime);
                        ws.get_Range("Q" + i.ToString()).Value2 = One.AdvenceAmount;
                        ws.get_Range("R" + i.ToString()).Value2 = CommonItem.X_yyyyMMdd(One.AdvenceReturnTime);
                        ws.get_Range("S" + i.ToString()).Value2 = One.AdvencePICName;
                        ws.get_Range("T" + i.ToString()).Value2 = One.BudgetAmount;
                        ws.get_Range("U" + i.ToString()).Value2 = One.In_StFu;
                        ws.get_Range("V" + i.ToString()).Value2 = One.In_PrFu;
                        ws.get_Range("W" + i.ToString()).Value2 = One.In_Su;
                        ws.get_Range("X" + i.ToString()).Value2 = One.In_DeSu;
                        ws.get_Range("Y" + i.ToString()).Value2 = One.In_ScSu;
                        ws.get_Range("Z" + i.ToString()).Value2 = One.In_PoSu;
                        ws.get_Range("AA" + i.ToString()).Value2 = One.In_MaSu;
                        ws.get_Range("AB" + i.ToString()).Value2 = One.In_O;
                        ws.get_Range("AC" + i.ToString()).Value2 = One.In_B;
                        ws.get_Range("AD" + i.ToString()).Value2 = One.In_Rem;
                        ws.get_Range("AE" + i.ToString()).Value2 = One.His_Amount;
                        ws.get_Range("AF" + i.ToString()).Value2 = One.Hi_Rem;
                        ws.get_Range("AG" + i.ToString()).Value2 = One.BudgetPay_Amount;
                        ws.get_Range("AH" + i.ToString()).Value2 = One.BuPa_Rem;
                        i++;
                    }

                    book.Save();
                    book.Close(false, Type.Missing, Type.Missing);

                    ws = null;
                    book = null;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (book != null)
                        book.Close(false, Type.Missing, Type.Missing);

                    if (app != null)
                        app.Quit();

                    ws = null;
                    book = null;
                    app = null;

                    GC.Collect();
                }

                List<Byte[]> lsByte = new List<byte[]>();

                FileStream fs = new FileStream(strTempPath, FileMode.Open);
                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                lsByte.Add(bytes);
                System.IO.File.Delete(strTempPath);

                Response.BufferOutput = false;

                Response.Charset = "UTF-8";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
                Response.ContentType = "application/octet-stream";

                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode("ProjectTemplate.xls"));
                foreach (Byte[] aByte in lsByte)
                {
                    Response.BinaryWrite(aByte);
                }
                Response.Flush();
                Response.End();

                return new EmptyResult();

                #endregion
            }
            else if (id == 2)
            {
                #region CreateTemplate

                NormalBudgetUploadModel M = new NormalBudgetUploadModel();
                M.U = this.CurrentUser;

                List<BudgetItem> lsTmp = M.GetCurrentBudget(Data.Select(o => o.BudgetGuid).ToList());

                if (Data.Count == Data.Count(o => o.ProjectCategoryID == "1"))
                {
                    return DownloadTemplate(1, lsTmp, false);
                }
                else if (Data.Count == Data.Count(o => o.ProjectCategoryID == "2"))
                {
                    return DownloadTemplate(2, lsTmp, false);
                }
                else if (Data.Count == Data.Count(o => o.ProjectCategoryID == "3"))
                {
                    return DownloadTemplate(3, lsTmp, false);
                }
                else if (Data.Count == Data.Count(o => o.ProjectCategoryID == "4" && o.ProjectTypeID == "JJ"))
                {
                    return DownloadTemplate("JJ", lsTmp, false);
                }
                else if (Data.Count == Data.Count(o => o.ProjectCategoryID == "4" && o.ProjectTypeID == "JW"))
                {
                    return DownloadTemplate("JW", lsTmp, false);
                }
                else
                {
                    ViewData["DB.Operation.Result"] = "请选择同一个编制单位，同一类别，同一类型的预算";
                    return View();
                }

                #endregion
            }
            else if (id == 3)
            {
                ActionResult R = null;

                #region CreateAppoverTemplate

                NormalBudgetUploadModel M = new NormalBudgetUploadModel();
                M.U = this.CurrentUser;

                List<BudgetItem> lsTmp = M.GetCurrentBudget(Data.Select(o => o.BudgetGuid).ToList());

                if (Data.Count == Data.Count(o => o.ProjectCategoryID == "1"))
                {
                    R = DownloadTemplate(1, lsTmp, true);
                }
                else if (Data.Count == Data.Count(o => o.ProjectCategoryID == "2"))
                {
                    R = DownloadTemplate(2, lsTmp, true);
                }
                else if (Data.Count == Data.Count(o => o.ProjectCategoryID == "3"))
                {
                    R = DownloadTemplate(3, lsTmp, true);
                }
                else if (Data.Count == Data.Count(o => o.ProjectCategoryID == "4" && o.ProjectTypeID == "JJ"))
                {
                    R = DownloadTemplate("JJ", lsTmp, true);
                }
                else if (Data.Count == Data.Count(o => o.ProjectCategoryID == "4" && o.ProjectTypeID == "JW"))
                {
                    R = DownloadTemplate("JW", lsTmp, true);
                }
                else
                {
                    ViewData["DB.Operation.Result"] = "请选择同一个编制单位，同一类别，同一类型的预算";
                    return View();
                }

                #endregion

                if (R != null)
                {
                    #region 设为审核中

                    if (Request.QueryString["IsAppover"] == "1")
                    {

                        HistoryItem His = new HistoryItem();

                        DBDataContext DB = new DBDataContext();
                        DB.Connection.Open();

                        DB.Transaction = DB.Connection.BeginTransaction();

                        try
                        {

                            List<wf_Budget> lsTmp_Approve = (from x in DB.wf_Budgets
                                                             where Data.Select(o => o.BudgetGuid).Contains(x.Guid)
                                                             select x).ToList();
                            foreach (wf_Budget oTmp in lsTmp_Approve)
                            {
                                His.AddHis(oTmp, DB);

                                oTmp.BudgetStatus = Convert.ToString((int)L_BudgetStatus.Approve);
                            }

                            DB.SubmitChanges();

                            DB.Transaction.Commit();
                        }
                        catch (Exception Ex)
                        {
                            ViewData["DB.Operation.Result"] = "[数据库操作失败] " + Ex.Message;

                            DB.Transaction.Rollback();
                        }
                        finally
                        {
                            DB.Connection.Close();
                            DB = null;
                        }
                    }

                    #endregion

                    return R;
                }
                else
                    return View();
            }
            else
            {
                ViewData["DB.Operation.Result"] = "没有任何下载";
                return View();
            }
        }

    }
}
